package com.qq.weixin.service;

import java.io.IOException;
import java.text.MessageFormat;
import java.util.List;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.qq.weixin.model.ResultInfo;
import com.qq.weixin.model.user.OpenidBatchInfo;
import com.qq.weixin.model.user.UserInfo;
import com.qq.weixin.util.Constants;

public class UserService {

	Logger logger = Logger.getLogger(getClass());
	private CloseableHttpClient httpclient = HttpClients.createDefault();

	/**
	 * 处理所有的用户信息
	 * 
	 * @param accessToken
	 * @param handler
	 */
	public void handleAllUser(String accessToken, UserHandler handler) {

		String nextOpenid = "";

		while (true) {
			OpenidBatchInfo openidBatchInfo = getOpenidBatch(accessToken,
					nextOpenid);

			if (!openidBatchInfo.getResultInfo().isSuccess()) {
				logger.error("获取 openidbatch出错, resultInfo:"
						+ openidBatchInfo.getResultInfo());
				return;
			}

			if (openidBatchInfo.getCount() > 0) {
				handleOpenidBatch(accessToken, openidBatchInfo.getOpenidList(),
						handler);
				nextOpenid = openidBatchInfo.getNextOpenid();
			} else {
				break;
			}
		}
	}

	private void handleOpenidBatch(String accessToken, List<String> openidList,
			UserHandler handler) {
		for (String openid : openidList) {
			UserInfo userInfo = getUserInfo(accessToken, openid);
			handler.handle(userInfo);
		}
	}

	/**
	 * 获取批量openid
	 * 
	 * @param accessToken
	 * @param nextOpenid
	 * @return
	 */
	public OpenidBatchInfo getOpenidBatch(String accessToken, String nextOpenid) {

		logger.info("----getOpenidBatch() nextOpenid=" + nextOpenid);

		if (nextOpenid == null) {
			nextOpenid = "";
		}
		HttpGet getReq = new HttpGet(
				MessageFormat
						.format("https://api.weixin.qq.com/cgi-bin/user/get?access_token={0}&next_openid={1}",
								accessToken, nextOpenid));

		OpenidBatchInfo userBatchInfo = new OpenidBatchInfo();

		CloseableHttpResponse getResp = null;
		try {
			getResp = httpclient.execute(getReq);
			String jsonstr = EntityUtils.toString(getResp.getEntity(),
					Constants.UTF_8);

			JSON json = JSON.parseObject(jsonstr);

			ResultInfo resultInfo = ResultInfo.convert(json);
			if (resultInfo.isSuccess()) {
				userBatchInfo = JSON.toJavaObject(json, OpenidBatchInfo.class);
			}
			userBatchInfo.setResultInfo(resultInfo);
		} catch (Exception e) {
			logger.error(e);
		} finally {
			if (getResp != null) {
				try {
					getResp.close();
				} catch (IOException e) {
					logger.error("", e);
				}
			}
		}

		return userBatchInfo;
	}

	/**
	 * 获取用户详细信息
	 * 
	 * @param accessToken
	 * @param openID
	 * @return
	 */
	public UserInfo getUserInfo(String accessToken, String openID) {
		HttpGet getReq = new HttpGet(
				MessageFormat
						.format("https://api.weixin.qq.com/cgi-bin/user/info?access_token={0}&openid={1}",
								accessToken, openID));

		UserInfo userInfo = new UserInfo();

		CloseableHttpResponse getResp = null;
		try {
			getResp = httpclient.execute(getReq);
			String jsonstr = EntityUtils.toString(getResp.getEntity(), "utf-8");
			JSON json = JSON.parseObject(jsonstr);
			ResultInfo resultInfo = ResultInfo.convert(json);
			if (resultInfo.isSuccess()) {
				userInfo = JSON.toJavaObject(json, UserInfo.class);
			}
			userInfo.setResultInfo(resultInfo);
		} catch (Exception e) {
			logger.error(e);
		} finally {
			if (getResp != null) {
				try {
					getResp.close();
				} catch (IOException e) {
					logger.error("", e);
				}
			}
		}

		return userInfo;
	}
}